<template>
  <div>
    <el-form ref="form" label-width="130px" :rules="rules" :model="form" v-loading="loading">
      <el-form-item label="出租类别：" prop="productType">
        <el-select
          v-model="form.productType"
          placeholder="请选择"
          :popper-append-to-body="false"
          @change="$refs.form.clearValidate()"
        >
          <el-option
            v-for="item in productTypeArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类：" prop="choosedCategoryArr">
        <el-cascader
          ref="categoryCascader"
          v-model="form.choosedCategoryArr"
          :options="categoryList"
          @change="categoryChange"
          key="categoryCascader"
        ></el-cascader>
      </el-form-item>

      <el-form-item
        label="设备品牌："
        prop="hgProductEquipmentLease.equipmentBrand"
        v-if="form.productType === productType.device.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductEquipmentLease.equipmentBrand"
          placeholder="请输入设备品牌"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="设备型号："
        prop="hgProductEquipmentLease.equipmentNo"
        v-if="form.productType === productType.device.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductEquipmentLease.equipmentNo"
          placeholder="请输入设备型号"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="出厂日期："
        prop="hgProductEquipmentLease.factoryDate"
        v-if="form.productType === productType.device.value"
      >
        <el-date-picker
          v-model="form.hgProductEquipmentLease.factoryDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item
        label="工作小时："
        prop="hgProductEquipmentLease.workHours"
        v-if="form.productType === productType.device.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductEquipmentLease.workHours"
          placeholder="请输入工作小时"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="整机序列号："
        prop="hgProductEquipmentLease.serialNo"
        v-if="form.productType === productType.device.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductEquipmentLease.serialNo"
          placeholder="请输入整机序列号"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="日租金："
        prop="hgProductMaterialLease.dayRent"
        v-if="form.productType === productType.buildStuff.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductMaterialLease.dayRent"
          placeholder="请输入日租金"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="月租金："
        prop="hgProductEquipmentLease.monthRent"
        v-if="form.productType === productType.device.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductEquipmentLease.monthRent"
          placeholder="请输入月租金"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="月租金：" prop="hgProductMaterialLease.monthRent" v-if="form.productType === productType.buildStuff.value">
        <el-input
          type="text"
          v-model="form.hgProductMaterialLease.monthRent"
          placeholder="请输入月租金"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="年租金："
        prop="hgProductMaterialLease.yearRent"
        v-if="form.productType === productType.buildStuff.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductMaterialLease.yearRent"
          placeholder="请输入年租金"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="台班租金："
        prop="hgProductEquipmentLease.classRent"
        v-if="form.productType === productType.device.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductEquipmentLease.classRent"
          placeholder="请输入台班租金"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="小时租金："
        prop="hgProductEquipmentLease.hourRent"
        v-if="form.productType === productType.device.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductEquipmentLease.hourRent"
          placeholder="请输入小时租金"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="数量："
        prop="hgProductMaterialLease.stock"
        v-if="form.productType === productType.buildStuff.value"
      >
        <el-input
          type="text"
          v-model="form.hgProductMaterialLease.stock"
          placeholder="请输入数量"
        >
          <template slot="append">/个/节/米/吨</template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="租赁状态"
        prop="hgProductEquipmentLease.leaseStatus"
        v-if="form.productType === productType.device.value"
      >
        <el-select
          v-model="form.hgProductEquipmentLease.leaseStatus"
          placeholder="请选择"
          :popper-append-to-body="false"
        >
          <el-option
            v-for="item in rentOutStatusArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="租赁状态"
        prop="hgProductMaterialLease.leaseStatus"
        v-if="form.productType === productType.buildStuff.value"
      >
        <el-select
          v-model="form.hgProductMaterialLease.leaseStatus"
          placeholder="请选择"
          :popper-append-to-body="false"
        >
          <el-option
            v-for="item in rentOutStatusArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品标题：" prop="productTitle">
        <el-input
          type="text"
          v-model="form.productTitle"
          placeholder="请输入商品标题"
        ></el-input>
      </el-form-item>

      <el-form
        ref="attrForm"
        label-width="130px"
        :rules="attrRules"
        :model="AttrForm"
        v-if="productAttr.length"
      >
        <el-form-item
          :label="item.title + '：'"
          :prop="'productAttr' + index"
          v-for="(item, index) in productAttr"
          :key="index"
        >
          <el-input
            type="text"
            v-model="AttrForm['productAttr' + index]"
            :placeholder="'请输入' + item.title"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-form-item label="商品图片：" prop="productImg" style="margin-bottom: 20px">
        <ImageUpload
          :imgSrc="require('@/assets/img/icon-upload2.png')"
          :limit="6"
          v-model="form.productImg"
        ></ImageUpload>
      </el-form-item>
      <el-form-item label="商品详情：" prop="intro" style="margin-bottom: 20px">
        <ImageUpload
          :imgSrc="require('@/assets/img/icon-upload2.png')"
          :limit="6"
          v-model="form.intro"
        ></ImageUpload>
      </el-form-item>
      <el-form-item label="联系人：" prop="addressName">
        <el-input
          type="text"
          v-model="form.addressName"
          placeholder="请输入联系人"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话：" prop="addressPhone">
        <el-input
          type="text"
          v-model="form.addressPhone"
          placeholder="请输入联系电话"
        ></el-input>
      </el-form-item>
      <el-form-item label="位置信息：" prop="areaValue">
        <el-cascader
          ref="areaCascader"
          :props="prop"
          v-model="form.areaValue"
          :options="areaList"
          key="areaCascader"
        ></el-cascader>
      </el-form-item>
    </el-form>
    
    <div class="flex-x-center">
        <el-button type="primary" class="submit-btn" @click="submit">立即发布</el-button>
    </div>
  </div>
</template>

<script>
import { rentOutStatus, sellType, productType, const2Arr } from "@/consts";
import { getCity } from "@/api/common.js";
import { getProductDetail } from '@/api/product'
import {
  getCategory,
  cateProductParam,
} from "@/api/product.js";
export default {
  name: "ProductRentOut",
  props:{
    id: ''
  },
  data() {
    return {
      productType,
      rentOutStatus,
      productTypeArr: const2Arr(productType),
      rentOutStatusArr: const2Arr(rentOutStatus),
      categoryList: [],
      productId: "",
      form: {
        choosedCategoryArr: "",
        areaValue: "",
        productType: productType.device.value, // 1设备 2建材
        putType: 3, // 1厂家 2二手 3租赁（租赁前端已拆分）
        categoryId: "", // 分类ID
        productTitle: "", // 商品标题
        productImg: "", // 商品图片
        intro: "", // 商品详情图片
        addressName: "", // 联系人
        addressPhone: "", //联系方式
        provinceId: "", // 省级ID
        province: "",
        cityId: "", // 市级ID
        city: "",
        areaId: "", // 地区ID
        area: "",
        productAttr: [], // 商品参数
        showPrice: "", // 展示价格 等同于售价
        address: "", // 地址详情 暂时没用
        productImg: "", //商品图片
        phone: "",
        code: "",

        // 出售设备
        hgProductEquipmentSell: {
          equipmentBrand: "", //设备品牌
          equipmentNo: "", // 设备型号
          serialNo: "", // 整机序列号
          factoryDate: "", //出厂日期
          workHours: "", // 工作小时
          price: "", // 售价
          paymentWay: "", //付款方式
          equipmentStatus: "", // 设备状态
          buyPrice: "", // 购机价格
          status: "", // 机况状态
        },
        // 出售建材
        hgProductMaterialSell: {
          stock: "",
          price: "",
          paymentWay: "",
        },
        // 租赁设备
        hgProductEquipmentLease: {
          equipmentBrand: "",
          equipmentNo: "",
          serialNo: "",
          factoryDate: "",
          workHours: "",
          monthRent: "",
          classRent: "",
          hourRent: "",
          leaseStatus: "", // 租赁状态 1-待租 2-已租
        },
        // 租赁建材
        hgProductMaterialLease: {
          dayRent: "",
          monthRent: "",
          yearRent: "",
          stock: "",
          leaseStatus: "", // 租赁状态 1-待租 2-已租
        },
        // 规格
        hgProductSkus: [],
      },
      AttrForm: {},
      attrRules: {},
      productAttr: [], //商品参数
      areaList: [],
      rules: {
        choosedCategoryArr: [
          { required: true, message: "分类不能为空", trigger: "change" },
        ],
        productTitle: [{ required: true, message: "商品标题不能为空", trigger: "blur" }],
        productImg: [{ required: true, message: "商品图片不能为空", trigger: "blur" }],
        addressName: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
        addressPhone: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
        intro: [{ required: true, message: "商品详情不能为空", trigger: "blur" }],
        areaValue: [{ required: true, message: "位置信息不能为空", trigger: "change" }],
        hgProductEquipmentLease: {
          equipmentBrand: [
            { required: true, message: "设备品牌不能为空", trigger: "blur" },
          ],
          equipmentNo: [{ required: true, message: "设备型号不能为空", trigger: "blur" }],
          factoryDate: [{ required: true, message: "出厂日期不能为空", trigger: "blur" }],
          workHours: [{ required: true, message: "工作小时不能为空", trigger: "blur" }],
          serialNo: [{ required: true, message: "整机序列号不能为空", trigger: "blur" }],
          monthRent: [{ required: true, message: "月租金不能为空", trigger: "blur" }],
          classRent: [{ required: true, message: "台班租金不能为空", trigger: "blur" }],
          hourRent: [{ required: true, message: "小时租金不能为空", trigger: "blur" }],
          leaseStatus: [{ required: true, message: "租赁状态不能为空", trigger: "change" }],
        },
        hgProductMaterialLease: {
          dayRent: [{ required: true, message: "日租金不能为空", trigger: "blur" }],
          monthRent: [{ required: true, message: "月租金不能为空", trigger: "blur" }],
          yearRent: [{ required: true, message: "年租金不能为空", trigger: "blur" }],
          stock: [{ required: true, message: "数量不能为空", trigger: "blur" }],
          leaseStatus: [{ required: true, message: "租赁状态不能为空", trigger: "change" }],
        },
        hgProductSkus: [],
      },
      loading: false,
      prop: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          const nodes = [];
          setTimeout(() => {
            // 构造查询条件
            let query = {
              p_code: node.value,
              level: node.level + 2,
            };
            //查询接口
            getCity(query).then((res) => {
              res.result.map((item) => {
                let obj = {
                  value: item.code,
                  label: item.name,
                  leaf: item.level == 4, // 节点级别，如果没有子节点就停止查询
                };
                nodes.push(obj);
              });
              //重新加载节点
              resolve(nodes);
            });
          }, 100);
        },
      },
    };
  },
  created(){
    if (this.id) {
      this.loading = true;
      this.getProductDetail();
    } else {
      this.getCity();
      this.getCategory();
    }
  },
  methods: {
    getProductDetail() {
      getProductDetail({ id: this.id }).then((res) => {
        let data = res.result;
        this.form = {
          choosedCategoryArr: [],
          areaValue: [],
          id: data.id,
          productType: data.product_type,
          putType: data.put_type,
          categoryId: data.category_id,
          productTitle: data.product_title, // 商品标题
          productImg: data.product_img, // 商品图片
          intro: data.intro, // 商品详情图片
          addressName: data.address_name, // 联系人
          addressPhone: data.address_phone, //联系方式
          provinceId: data.province_id, // 省级ID
          province: data.province,
          cityId: data.city_id, // 市级ID
          city: data.city,
          areaId: data.area_id, // 地区ID
          area: data.area,
          productAttr: [], // 商品参数
          showPrice: "", // 展示价格 等同于售价
          address: "", // 地址详情 暂时没用
          phone: "",
          code: "",
          // 出售设备
						hgProductEquipmentSell:{  
							equipmentBrand: '',
							equipmentNo: '',
							serialNo: '',
							factoryDate: '',
							workHours: '',
							price: '',
							paymentWay: '',
							equipmentStatus: '',
							buyPrice: '',
							status: ''
						}, 
						// 出售建材
						hgProductMaterialSell:{  
							stock: '',
							price: '',
							paymentWay: '',
						},
						// 租赁设备
						hgProductEquipmentLease:{
							equipmentBrand: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.equipmentBrand : '',
							equipmentNo: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.equipmentNo : '',
							serialNo: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.serialNo : '',
							factoryDate: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.factoryDate : '',
							workHours: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.workHours : '',
							monthRent: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.monthRent : '',
							classRent: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.classRent : '',
							hourRent: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.hourRent : '',
							leaseStatus: data.hgProductEquipmentLease ? data.hgProductEquipmentLease.leaseStatus : '', // 租赁状态 1-待租 2-已租
						},
						// 租赁建材
						hgProductMaterialLease:{
							dayRent: data.hgProductMaterialLease ? data.hgProductMaterialLease.dayRent : '',
							monthRent: data.hgProductMaterialLease ? data.hgProductMaterialLease.monthRent : '',
							yearRent: data.hgProductMaterialLease ? data.hgProductMaterialLease.yearRent : '',
							stock: data.hgProductMaterialLease ? data.hgProductMaterialLease.stock : '',
							leaseStatus: data.hgProductMaterialLease ? data.hgProductMaterialLease.leaseStatus : '', // 租赁状态 1-待租 2-已租
						},
          hgProductSkus: data.hgProductSkuList
            ? data.hgProductSkuList.map((item) => ({
                skuName: item.skuName,
                skuPrice: item.skuPrice,
                skuStock: item.skuStock,
              }))
            : [],
        };
        // 分类
        getCategory().then((res) => {
          this.categoryList = this.formatCategory(res.result);

          const parent3 = this.getParentCategory(res.result, this.form.categoryId);
          const parent2 = this.getParentCategory(res.result, parent3);
          const parent1 = this.getParentCategory(res.result, parent2);
          this.$nextTick(() => {
            this.form.choosedCategoryArr = [
              parent1,
              parent2,
              parent3,
              this.form.categoryId,
            ];
          });
        });

        this.$nextTick(() => {
          this.form.areaValue = [
            this.form.provinceId,
            this.form.cityId,
            this.form.areaId,
          ];
        });

        const attrs = JSON.parse(data.product_attr);
        cateProductParam({ id: this.form.categoryId }).then((cates) => {
          if (cates.result.categoryAttr) {
            const allCategory = cates.result.categoryAttr.split(",");
            for (var i = 0; i < allCategory.length; i++) {
              const isExitsAttr = attrs.find((item) => item.title === allCategory[i]);
              this.productAttr.push({
                title: allCategory[i],
                value: isExitsAttr ? isExitsAttr.value : "",
              });
              this.$set(
                this.AttrForm,
                "productAttr" + i,
                isExitsAttr ? isExitsAttr.value : ""
              );
              this.$set(this.attrRules, "productAttr" + i, [
                { required: true, message: allCategory[i] + "不能为空", trigger: "blur" },
              ]);
            }
          }
        });
        this.loading = false;
      });
    },
    getCity() {
      getCity({ level: 2, p_code: "" }).then((res) => {
        this.areaList = res.result.map((item) => ({
          value: item.code,
          label: item.name,
        }));
      });
    },
    getCategory() {
      getCategory().then((res) => {
        this.categoryList = this.formatCategory(res.result);
      });
    },
    getParentCategory(categoryList, categoryId) {
      let isHas = false;
      let parentId = "";
      getParent(categoryList);

      function getParent(categoryList) {
        categoryList.forEach((item) => {
          if (item.id == categoryId) {
            isHas = true;
            parentId = item.parentId;
          }
        });

        if (!isHas) {
          categoryList.forEach((item) => {
            if (item.children && item.children.length) {
              getParent(item.children);
            }
          });
        }
      }
      return parentId;
    },
    formatCategory(data) {
      data.forEach((item) => {
        item.label = item.categoryTitle;
        item.value = item.id;
        if (item.children) {
          this.formatCategory(item.children);
        }
      });
      return data;
    },
    getCheckedNodes() {
      return this.$refs.areaCascader.getCheckedNodes();
    },
    categoryChange(e) {
      if (!e.length) return;
      this.$nextTick(() => {
        if (e.length !== 4) {
          this.$refs.categoryCascader.$refs.panel.clearCheckedNodes();
          this.productAttr = [];
          return this.$modal.msgError("请选择最后一级分类");
        }
        this.productAttr = [];
        cateProductParam({ id: e[3] }).then((res) => {
          if (res.result && res.result.categoryAttr) {
            res.result.categoryAttr.split(",").forEach((item, index) => {
              this.productAttr.push({ title: item, value: "" });
              this.$set(this.AttrForm, "productAttr" + index, "");
              this.$set(this.attrRules, "productAttr" + index, [
                { required: true, message: item + "不能为空", trigger: "blur" },
              ]);
            });
          }
        });
      });
    },
    submit() {
      const promise = new Promise((resolve, reject) => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            resolve();
          }
        });
      });
      const promiseArr = [promise];
      if (this.productAttr.length) {
        promiseArr.push(
          new Promise((resolve, reject) => {
            this.$refs["attrForm"].validate((valid) => {
              if (valid) {
                resolve();
              }
            });
          })
        );
      }

      Promise.all(promiseArr).then((res) => {
        const allNodes = this.getCheckedNodes()[0].pathNodes;
        this.form.provinceId = allNodes[0].value;
        this.form.province = allNodes[0].label;
        this.form.cityId = allNodes[1].value;
        this.form.city = allNodes[1].label;
        this.form.areaId = allNodes[2].value;
        this.form.area = allNodes[2].label;

        const attrs = Object.keys(this.AttrForm);
        const arr = []
        for(var i = 0; i < this.productAttr.length; i++){
          arr.push({ title: this.productAttr[i].title, value: this.AttrForm[attrs[i]] });
        }
       
        this.form.productAttr = JSON.stringify(arr);
        this.form.categoryId = this.form.choosedCategoryArr[3];
        // 租赁商品
        if(this.form.productType === productType.device.value){
            this.form.showPrice = this.form.hgProductEquipmentLease.monthRent
        }
        // 租赁建材
        else{
            this.form.showPrice = this.form.hgProductMaterialLease.monthRent
        }
        this.form.isSku = 2;

        this.$emit("submit", this.form);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.textarea {
  min-height: 186px;
}

::v-deep .el-form-item__label {
  line-height: 56px;
  font-size: 18px;
  width: 120px;
}

::v-deep .el-input__inner,
::v-deep .el-textarea__inner,
::v-deep .el-date-editor {
  width: 548px;
  height: 56px;
  font-size: 18px;
}

::v-deep .el-form-item__content {
  width: 548px;
}

::v-deep .el-select-dropdown__item {
  font-size: 16px;
}

::v-deep .textarea > textarea {
  height: 180px;
  padding: 20px;
}

.btn-wrapper {
  margin-top: 30px;

  .appraise {
    display: flex;
    align-items: center;
    font-weight: normal;
    font-size: 14px;
    color: #333333;
    margin-right: 50px;

    .price {
      font-weight: normal;
      font-size: 22px;
      color: #f42d1f;
    }
  }
}

.submit-btn {
  width: 548px;
  height: 60px;
  border-radius: 10px;
  font-size: 20px;
}

.gu-btn {
  position: relative;
  left: 4px;
  margin: 30px 0;
  width: 548px;
  height: 60px;
  border-radius: 10px;
  font-size: 20px;
}

.used-btn {
  width: 200px;
}

.sku-btn {
  width: 200px;
  height: 56px;
  font-size: 18px;
}
</style>
